<template>
  <el-dialog
    v-if="dialogVisible"
    width="500px"
    :title="title"
    :lock-scroll="false"
    :visible.sync="dialogVisible"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    append-to-body
    @close="handleClose"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item prop="avatar" label="用户头像">
        <CropperImage :img-src="form.avatar" @input="handleAvatarInput">
          <i class="fa-solid fa-user" />
        </CropperImage>
      </el-form-item>
      <el-form-item prop="username" label="用户账号">
        <el-input v-model="form.username" placeholder="请输入用户账号" />
      </el-form-item>
      <el-form-item v-if="type === 'add'" prop="password" label="用户密码">
        <el-input v-model="form.password" placeholder="请输入用户密码" onkeyup="value = value.replace(/[\u4E00-\u9FA5]/g,'')" show-password>
          <template slot="append">
            <PasswordLevel :password="form.password" @pwdLevel="passwordLevelHandle" />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="nickName" label="用户姓名">
        <el-input v-model="form.nickName" placeholder="请输入用户姓名" />
      </el-form-item>
      <el-form-item prop="sex" label="性别">
        <el-select v-model="form.sex" class="w_100" placeholder="请选择性别">
          <el-option :value="1" label="男" />
          <el-option :value="2" label="女" />
        </el-select>
      </el-form-item>
      <el-form-item prop="phoneNum" label="手机号码">
        <el-input v-model="form.phoneNum" placeholder="请输入手机号码" />
      </el-form-item>
      <el-form-item prop="email" label="电子邮箱">
        <el-input v-model="form.email" placeholder="请输入电子邮箱" />
      </el-form-item>
      <el-form-item prop="dept.id" label="部门">
        <TreeSelect :props="{children: 'children', label: 'name', value: 'id'}" :data="deptTreeData" :value="form.dept.id" filterable @input="deptTreeInput" />
      </el-form-item>
      <el-form-item prop="roleList" label="角色">
        <el-select v-model="form.roleIdList" class="w_100" multiple placeholder="请选择角色" @change="roleSelectChange">
          <el-option
            v-for="item in roleList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { add, edit, getInfo } from '@/api/user'
import { getTree } from '@/api/dept'
import { getAll } from '@/api/role'

export default {
  name: 'SaveOrEditVue',
  components: {
    TreeSelect: () => import('@/components/TreeSelect/index.vue'),
    CropperImage: () => import('@/components/CropperImage/index.vue'),
    PasswordLevel: () => import('@/views/user/components/PasswordLevel.vue')
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: 'add'
    },
    id: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      dialogVisible: this.visible,
      title: '新增',
      form: {
        avatar: '',
        username: '',
        password: '',
        nickName: '',
        sex: undefined,
        phoneNum: '',
        email: '',
        dept: {
          id: undefined
        },
        roleIdList: [],
        roleList: []
      },
      deptTreeData: [],
      roleList: [],
      rules: {
        avatar: [{ required: true, message: '请上传用户头像', trigger: 'blur' }],
        username: [
          { required: true, message: '请输入用户账号', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入用户密码', trigger: 'blur' },
          { min: 5, max: 20, message: '长度在 5 到 50 个字符', trigger: 'blur' }
        ],
        sex: [{ required: true, message: '请选择性别', trigger: 'blur' }],
        nickName: [{ required: true, message: '请输入用户姓名', trigger: 'blur' }],
        phoneNum: [{ validator: this.checkPhone, required: false, trigger: 'blur' }],
        email: [{ validator: this.checkEmail, required: false, trigger: 'blur' }],
        'dept.id': [{ required: true, message: '请选择部门', trigger: 'blur' }],
        roleList: [{ required: true, message: '请选择角色', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getDeptTree()
    this.getRoleList()
    switch (this.type) {
      case 'add':
        this.title = '新增'
        break
      case 'edit':
        this.title = '编辑'
        getInfo(this.id).then(res => {
          this.form = res.data

          this.form.dept.id = this.form.dept.id.toString()

          if (this.form.roleList) {
            this.form.roleIdList = []
            this.form.roleList.forEach(item => this.form.roleIdList.push(item.id))
          }
        })
        break
      default:
        break
    }
  },
  methods: {
    getRoleList() {
      getAll().then(res => {
        this.roleList = res.data
      })
    },
    getDeptTree() {
      getTree({}).then(res => {
        this.deptTreeData = res.data
      })
    },
    deptTreeInput(data) {
      this.form.dept.id = data.toString()
    },
    roleSelectChange(data) {
      this.form.roleList = []
      data.forEach(roleId => this.form.roleList.push({ id: roleId }))
      this.$forceUpdate()
    },
    handleSubmit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          switch (this.type) {
            case 'add':
              add(this.form).then(res => {
                this.$message.success('添加成功')
                this.handleGetList()
                this.handleClose()
              })
              break
            case 'edit':
              edit(this.form).then(res => {
                this.$message.success('编辑成功')
                this.handleGetList()
                this.handleClose()
              })
              break
            default:
              break
          }
        }
      })
    },
    passwordLevelHandle(level) {
      this.form.passwordLevel = level
    },
    checkPhone(rule, value, callback) {
      if (value) {
        const reg = /^1[3|4|5|7|8|9][0-9]\d{8}$/
        if (reg.test(value)) {
          callback()
        } else {
          return callback(new Error('请输入正确的手机号码'))
        }
      }
      callback()
    },
    checkEmail(rule, value, callback) {
      if (value) {
        const reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
        if (reg.test(value)) {
          callback()
        } else {
          return callback(new Error('请输入正确的电子邮箱'))
        }
      }
      callback()
    },
    handleAvatarInput(value) {
      this.form.avatar = value
    },
    handleGetList() {
      this.$emit('getList')
    },
    handleClose() {
      this.$emit('handleClose')
    }
  }
}
</script>

<style scoped lang="scss">
</style>
